package org.cweili.vehicle.service.admin

import org.cweili.vehicle.entity.Customer
import org.cweili.vehicle.entity.Journey
import org.cweili.vehicle.service.BaseService
import org.cweili.vehicle.util.Const
import org.cweili.vehicle.util.JSON
import org.cweili.vehicle.util.Utils
import org.directwebremoting.annotations.RemoteProxy
import org.directwebremoting.spring.SpringCreator
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

import com.alibaba.fastjson.JSONArray

/**
 * 管理员班次服务
 *
 * @author Cweili
 * @version 2013年7月27日 下午11:17:42
 *
 */
@RemoteProxy(creator = SpringCreator.class)
@Service
class AdminJourneyService extends BaseService {

	Page<Journey> getList(String json) {
		def obj = JSON.parseObject(json)

		def verifyStatus = JSON.getByte(obj, "verifyStatus")
		def page = JSON.getInteger(obj, "page")

		return journeyRepository.findByVerifyStatus(verifyStatus, new PageRequest(page,
		Const.PAGE_SIZE, Sort.Direction.DESC, "id"))
	}

	boolean del(String json) {
		try {
			def array = JSONArray.parseArray(json)

			for (obj in array) {
				journeyRepository.delete(Integer.parseInt(obj.toString()))
			}
		} catch (Exception e) {
			log.error(e + json, e)
			return false
		}
		return true
	}

	boolean save(String json) {
		def obj = JSON.parseObject(json)

		def verifyStatus = JSON.getByte(obj, "verifyStatus")
		def id = JSON.getInteger(obj, "id")
		def journeyTime = JSON.getString(obj, "journeyTime")
		def route = JSON.getString(obj, "route")
		def remark = JSON.getString(obj, "remark")
		def vehicleLicensePlate = JSON.getString(obj, "vehicleLicensePlate")
		def driverNumber = JSON.getString(obj, "driverNumber")

		if (verifyStatus == 0 || Utils.isEmpty(journeyTime, route)) {
			return false
		}

		def journey
		if (id > 0) {
			journey = journeyRepository.findOne(id)
			if (!journey) {
				return false
			}
		} else {
			journey = new Journey(
					commitCustomer : getCustomer(),
					commitDate : new Date()
					)
		}

		if (!Utils.isEmpty(vehicleLicensePlate)) {
			def vehicle = vehicleRepository.findByLicensePlate(vehicleLicensePlate)
			if (vehicle) {
				journey.vehicle = vehicle
			} else {
				return false
			}
		}

		if (!Utils.isEmpty(driverNumber)) {
			def driver = customerRepository.findByNumber(driverNumber)
			if (driver) {
				journey.driver = driver
			} else {
				return false
			}
		}

		journey.journeyTime = journeyTime
		journey.route = route
		journey.remark = remark
		journey.verifyCustomer = getCustomer()
		journey.verifyDate = new Date()
		journey.verifyStatus = verifyStatus

		return journeyRepository.save(journey)
	}
}
